package com.squirrel.serialportcore.machine.operator.impl;

import com.squirrel.serialportcore.common.CommonBase;
import com.squirrel.serialportcore.common.ContentBase;
import com.squirrel.serialportcore.exception.CoreException;
import com.squirrel.serialportcore.machine.operator.BasicsOperator;
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 基础操作实现类
 *
 * @author Squbi
 * @date 2021/3/4 17:53
 */
@Component
public class BasicsOperatorImpl implements BasicsOperator {
    private static final Logger logger = LoggerFactory.getLogger(BasicsOperatorImpl.class);

    @Override
    public SerialPort getSerialPort(String name) {
        SerialPort serialPort = ContentBase.getSerialPortMap().get(name);
        if (serialPort == null) {
            throw new CoreException(logger, " 线程 {} 访问的串口不存在 {} ", Thread.currentThread().getId(), name);
        }
        return serialPort;
    }

    @Override
    public List<String> getPortNameList() {
        return new ArrayList<>(ContentBase.getSerialPortMap().keySet());
    }

    @Override
    public SerialPort openSerialPort(String portName) {
        CommPortIdentifier commPortIdentifier = CommonBase.getSerialPortsIdentifier().get(portName);
        if (commPortIdentifier == null) {
            throw new CoreException(logger, " 打开串口错误 串口 {} 不存在", portName);
        }
        SerialPort serialPort;
        try {
            serialPort = (SerialPort) commPortIdentifier.open(portName, 1000);
        } catch (PortInUseException e) {
            throw new CoreException(logger, e, " 串口 {} 打开失败 原因 {}", portName, e.getMessage());
        }
        return serialPort;
    }
}
